<template>
	<div class="edit-page-wrap">
		<Head title="电桩信息">
			<template #content>
				<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px" class="edit-form-wrap">
					<el-form-item label="归属电站" prop="stationId">
						<qc-select v-if="!id" :value="ruleForm.stationId" :remote="true" :filterable="true"
							:options="optionsS.station" placeholder="请选择归属电站" @change="handleChangeStation">
						</qc-select>
						<div v-else>{{ ruleForm.stationName }}</div>
					</el-form-item>
					<el-form-item label="品牌型号" prop="brandModel">
						<el-cascader v-if="!id" ref="brandModelRef" popper-class="qc-cascader"
							v-model="ruleForm.brandModel" :options="optionsS.brandModel"
							@change="handleChangeBrandModel" placeholder="请选择品牌型号" clearable />
						<div v-else>{{ ruleForm.brandModelName }}</div>
					</el-form-item>
					<el-form-item v-if="webType === 'pnd'" label="电桩编码" prop="equipmentCode">
						<el-input v-model.trim="ruleForm.equipmentCode" placeholder="请输入电桩编码" maxlength="14"
							clearable />
					</el-form-item>
					<el-form-item v-if="webType !== 'pnd' && id" label="电桩编码" required>
						<div>{{ ruleForm.equipmentCode }}</div>
					</el-form-item>
					<el-form-item label="协议版本" prop="version">
						<qc-select :value="ruleForm.version" :options="optionsS.version" placeholder="请选择协议版本"
							@change="handleChangeVersion">
						</qc-select>
					</el-form-item>
					<el-form-item label="终端数量" class="has-tips">
						<div>{{ ruleForm.equipmentGunNumber }}</div>
						<div class="tip">
							<div class="icon"></div>
							温馨提示：多终端电桩会自动生成多个终端，在桩编码、桩名称后添加后缀01、02、03，从而生成相应终端的编号、名称
						</div>
					</el-form-item>
					<el-form-item label="电桩名称" prop="equipmentName">
						<el-input v-model.trim="ruleForm.equipmentName" placeholder="请输入电桩名称" maxlength="30"
							clearable />
					</el-form-item>
					<el-form-item label="电桩数量" prop="count">
						<el-input v-model.trim="ruleForm.count" placeholder="请输入新增电桩数量" maxlength="30" clearable />
					</el-form-item>
					<el-form-item label="通讯运营商" prop="communicationOperator">
						<el-radio-group v-model="ruleForm.communicationOperator"
							v-for="(item, index) in optionsS.communicationOperator" :key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="网络链接类型" prop="communicationType">
						<qc-select :value="ruleForm.communicationType" :options="optionsS.networkLinkType"
							placeholder="请选择网络链接类型" @change="handleChangeType">
						</qc-select>
					</el-form-item>
					<el-form-item v-if="ruleForm.communicationType === '1'" label="SIM卡号" prop="numberSim">
						<el-input v-model.trim="ruleForm.numberSim" placeholder="请输入SIM卡号" maxlength="30" clearable />
					</el-form-item>
					<el-form-item label="车位号" prop="parkNo">
						<el-input v-model.trim="ruleForm.parkNo" placeholder="请输入车位号" maxlength="30" clearable />
					</el-form-item>
					<el-form-item label="有无地锁" prop="parkLock">
						<el-radio-group v-model="ruleForm.parkLock" v-for="(item, index) in PILE_SIM" :key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
			</template>
		</Head>
		<Head title="运营信息">
			<template #content>
				<el-form ref="ruleFormOrgRef" :model="ruleForm" :rules="rules" label-width="140px"
					class="edit-form-wrap">
					<el-form-item label="价格设置" prop="priceSet">
						<el-radio-group v-model="ruleForm.priceSet" v-for="(item, index) in optionsS.priceSet"
							:key="index" :disabled="isPriceSet">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="ruleForm.priceSet === '2'" label="选择计费模板" prop="costTemplateId">
						<qc-select :value="ruleForm.costTemplateId" :remote="true" :filterable="true"
							:options="optionsS.template" placeholder="请选择选择计费模板" @change="handleChangeTemplate">
						</qc-select>
						<el-button type="primary" @click="clickTemplate" :disabled="!ruleForm.costTemplateId"
							class="item-btn">查看计费</el-button>
					</el-form-item>
				</el-form>
			</template>
		</Head>
		<Head title="硬件信息">
			<template #content>
				<el-form ref="ruleFormCURef" :model="ruleForm" :rules="rules" label-width="140px"
					class="edit-form-wrap">
					<el-form-item label="电桩国标" prop="equipmentStandard">
						<el-radio-group v-model="ruleForm.equipmentStandard"
							v-for="(item, index) in optionsS.equipmentStandard" :key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="充电模块品牌型号" prop="chargingModuleBrandModel">
						<el-input v-model.trim="ruleForm.chargingModuleBrandModel" placeholder="请输入充电模块品牌型号"
							maxlength="30" clearable />
					</el-form-item>
					<el-form-item label="充电枪线品牌型号" prop="chargingGunCableBrandModel">
						<el-input v-model.trim="ruleForm.chargingGunCableBrandModel" placeholder="请输入充电枪线品牌型号"
							maxlength="30" clearable />
					</el-form-item>
					<el-form-item label="电桩屏幕品牌" prop="equipmentScreenBrand">
						<el-input v-model.trim="ruleForm.equipmentScreenBrand" placeholder="请输入电桩屏幕品牌" maxlength="30"
							clearable />
					</el-form-item>
					<el-form-item label="电桩程序" prop="equipmentProcedure">
						<el-input v-model.trim="ruleForm.equipmentProcedure" placeholder="请输入电桩程序" maxlength="30"
							clearable />
					</el-form-item>
					<el-form-item label="设备生产日期" prop="productionDate">
						<el-date-picker v-model="ruleForm.productionDate" popper-class="qc-date" type="date"
							placeholder="请选择设备生产日期" valueFormat="YYYY-MM-DD" prefix-icon="Clock" />
					</el-form-item>
				</el-form>
			</template>
		</Head>
		<div class="edit-btn-wrap">
			<el-button type="primary" plain @click="back">取消</el-button>
			<el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
		</div>
		<DialogPrice ref="dialogPriceRef"></DialogPrice>
	</div>
</template>

<script lang="ts" setup>
	import type { FormInstance, FormRules } from 'element-plus';
	import Head from '@/components/head/index.vue';
	import DialogPrice from '../components/dialogPrice.vue';
	import {
		queryAllStation,
		equipmentBrandAndModelTreeData,
		queryCostTemplateByProtocolVersion,
		addEquipmentBatch,
		updateEquipment,
		queryEquipment,
		queryByStationIdAndProtocolVersionId,
	} from '@/service/apis/pile';
	import { queryDicByParent } from '@/service/apis/api';
	import { PILE_SIM } from '@/utils/dictionaries';
	import { IS_INTEGER } from '@/utils/verify';

	const webType = import.meta.env.VITE_ENV_TYPE;

	const router = useRouter();
	const route = useRoute();
	const {
		query: { id, stationId },
	} = route;
	const ruleFormRef = ref<FormInstance>();
	const ruleFormOrgRef = ref<FormInstance>();
	const ruleFormCURef = ref<FormInstance>();
	const dialogPriceRef = ref();

	let optionsS = reactive({
		station: [] as any,
		brandModel: [] as any,
		version: [] as any,
		communicationOperator: [] as any,
		networkLinkType: [] as any,
		priceSet: [] as any,
		template: [] as any,
		equipmentStandard: [] as any,
	});

	queryDicByParent({
		listDtos: [
			'protocolVersion',
			'communicationOperator',
			'priceSet',
			'equipmentStandard',
			'networkLinkType',
		],
	}).then((res : any) => {
		if (res) {
			console.log('ddd--', res);
			optionsS.version = res.protocolVersion;
			optionsS.communicationOperator = res.communicationOperator;
			optionsS.networkLinkType = res.networkLinkType;
			optionsS.priceSet = res.priceSet;
			optionsS.equipmentStandard = res.equipmentStandard;
			// if (optionsS.version.length > 1) {
			// 	ruleForm.version = optionsS.version[1]
			// }
			// if (optionsS.networkLinkType.length > 0) {
			// 	ruleForm.communicationType = optionsS.networkLinkType[0]
			// }
		}
	});

	const orgId = ref('');
	const getTemplateVersion = () => {
		queryCostTemplateByProtocolVersion({
			value: ruleForm.version,
			operatorId: orgId.value,
		}).then((res : any) => {
			if (res) {
				optionsS.template = [...res.list];
			}
		});
	};

	if (!id) {
		// 获取归属运营商
		queryAllStation({}).then((res : any) => {
			if (res) {
				nextTick(() => {
					optionsS.station = [...res];
				});
			}
		});
		//获取品牌型号数据
		equipmentBrandAndModelTreeData({}).then((res : any) => {
			if (res) {
				nextTick(() => {
					optionsS.brandModel = [...res];
				});
			}
		});
	}

	let isWatch = ref(true);
	if (id) {
		isWatch.value = false;
		queryEquipment({ id: id }).then((res : any) => {
			if (res) {
				for (const key in ruleForm) {
					if (res[key]) {
						ruleForm[key] = res[key];
					}
				}
				ruleForm.brandModel = [res.equipmentBrand, res.equipmentModel];
				ruleForm.brandModelName = `${res.equipmentBrandName}/${res.equipmentModelName}`;
				ruleForm.communicationType = String(res.communicationType);
				ruleForm.priceSet = String(res.priceSet);
				ruleForm.equipmentStandard = String(res.equipmentStandard);
				orgId.value = res.operatorId;
				if (ruleForm.priceSet === '2') {
					ruleForm.costTemplateId =
						res.stationCostBatchNumberInfoPOList[0]?.costTemplateId || '';
					getTemplateVersion();
				}
				nextTick(() => {
					isWatch.value = true;
				});
				console.log('ruleForm.costTemplateId----', ruleForm.costTemplateId);
			}
		});
	}

	let ruleForm : any = reactive({
		id: '',
		stationId: undefined as any, // 归属电站
		stationName: '', // 归属电站名称
		brandModel: [] as any, // 品牌型号
		brandModelName: '', // 品牌型号名称
		equipmentBrand: '', // 品牌
		equipmentModel: '', //型号
		equipmentCode: '', //电桩编码
		version: undefined as unknown, // 协议版本
		equipmentGunNumber: '', // 终端数量
		equipmentName: '', //电桩名称
		count: '',//批量添加数量
		communicationType: undefined as unknown, //通讯模块类别
		communicationOperator: '0', //通讯运营商
		// isSim: false, //有无SIM
		numberSim: '', //SIM卡号
		parkNo: '', //车位号
		parkLock: false, //有无地锁
		priceSet: '1', //价格设置
		costTemplateId: undefined as unknown, // 选择计费模板
		stationCostBatchNumberInfoPOList: [] as any,
		equipmentStandard: '0', //电桩国标
		chargingModuleBrandModel: '', //充电模块品牌型号
		chargingGunCableBrandModel: '', //充电枪线品牌型号
		equipmentScreenBrand: '', //电桩屏幕品牌
		equipmentProcedure: '', //电桩程序
		productionDate: new Date().toISOString().split('T')[0], //设备生产日期
	});
	const rules = reactive<FormRules>({
		stationId: [
			{ required: true, message: '请选择归属电站', trigger: ['blur', 'change'] },
		],
		brandModel: [
			{ required: true, message: '请选择品牌型号', trigger: ['blur', 'change'] },
		],
		equipmentCode: [
			{ required: true, message: '请输入电桩编码', trigger: 'blur' },
			{
				pattern: IS_INTEGER,
				message: '请输入正确的电桩编码（只支持数字）',
				trigger: 'blur',
			},
		],
		version: [
			{ required: true, message: '请选择协议版本', trigger: ['blur', 'change'] },
		],
		equipmentName: [
			{ required: true, message: '请输入电桩名称', trigger: 'blur' },
		],
		count: [
			{ required: true, message: '请输入新增电桩数量', trigger: 'blur' },
		],
		communicationType: [
			{
				required: true,
				message: '请选择网络链接类型',
				trigger: ['blur', 'change'],
			},
		],
		priceSet: [
			{ required: true, message: '请选择价格设置', trigger: ['blur', 'change'] },
		],
		costTemplateId: [
			{
				required: true,
				message: '请选择选择计费模板',
				trigger: ['blur', 'change'],
			},
		],
		equipmentStandard: [
			{ required: true, message: '请选择电桩国标', trigger: ['blur', 'change'] },
		],
		productionDate: [
			{
				required: true,
				message: '请选择设备生产日期',
				trigger: ['blur', 'change'],
			},
		],
	});

	if (stationId) {
		ruleForm.stationId = stationId;
	}

	const handleChangeStation = (e : any) => {
		ruleForm.stationId = e;
		if (ruleForm.stationId) {
			const obj = optionsS.station.find((item : any) => item.value === e);
			if (obj) {
				orgId.value = obj.operatorId;
			}
		} else {
			orgId.value = '';
		}
	};

	const handleChangeType = (e : any) => {
		ruleForm.communicationType = e;
	};

	const handleChangeTemplate = (e : any) => {
		ruleForm.costTemplateId = e;
		ruleForm.stationCostBatchNumberInfoPOList = [
			{
				costTemplateId: e,
			},
		];
	};

	const brandModelRef = ref();
	const handleChangeBrandModel = (e : any) => {
		ruleForm.brandModel = e;
		ruleForm.equipmentBrand = e[0];
		ruleForm.equipmentModel = e[1];
		const node = brandModelRef.value?.getCheckedNodes()[0];
		ruleForm.equipmentGunNumber = node.data.number;
	};

	const handleChangeVersion = (e : any) => {
		ruleForm.version = e;
		if (!ruleForm.version) {
			optionsS.template = [];
			isPriceSet.value = false;
		}
	};

	watch(
		() => [ruleForm.version, ruleForm.priceSet],
		() => {
			if (!isWatch.value) return;
			if (ruleForm.priceSet === '2' && ruleForm.costTemplateId) {
				ruleForm.costTemplateId = undefined as any;
				setTimeout(() => {
					ruleFormOrgRef.value?.clearValidate('costTemplateId');
				});
			}
			if (ruleForm.priceSet === '2' && ruleForm.version) {
				getTemplateVersion();
			}
		}
	);

	const isPriceSet = ref(false);
	watch(
		() => [ruleForm.stationId, ruleForm.version],
		() => {
			if (!isWatch.value) return;
			if (ruleForm.stationId && ruleForm.version) {
				queryByStationIdAndProtocolVersionId({
					stationId: ruleForm.stationId,
					protocolVersion: ruleForm.version,
				}).then((res : any) => {
					if (res) {
						isPriceSet.value = false;
						// ruleForm.priceSet = '1';
						ruleForm.costTemplateId = undefined as any;
					} else {
						isPriceSet.value = true;
						ruleForm.priceSet = '2';
						ruleForm.costTemplateId = undefined as any;
					}
				});
			}
		}
	);

	const clickTemplate = () => {
		dialogPriceRef.value?.show(ruleForm.costTemplateId);
	};

	const back = () => {
		router.go(-1);
	};

	const emit = defineEmits(['clear-cache']);
	const onSubmit = async () => {
		console.log('ruleForm----', ruleForm);
		if (!ruleFormRef.value || !ruleFormOrgRef.value || !ruleFormCURef.value)
			return;
		let flag = true;
		let objError = {} as any;
		await Promise.all([
			ruleFormRef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
			ruleFormOrgRef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
			ruleFormCURef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
		]);
		if (!flag) {
			for (const key in ruleForm) {
				if (objError[key]) {
					ruleFormRef.value.scrollToField(key);
					ruleFormOrgRef.value.scrollToField(key);
					ruleFormCURef.value.scrollToField(key);
					break;
				}
			}
			return;
		}
		if (id) {
			updateEquipment(ruleForm).then((res : any) => {
				emit('clear-cache');
				back();
			});
		} else {
			addEquipmentBatch(ruleForm).then((res : any) => {
				emit('clear-cache');
				back();
			});
		}
	};
</script>